package tech.aistar.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import tech.aistar.config.AlipayConfig;
import tech.aistar.pojo.entity.Orders;
import tech.aistar.service.OrderService;
import tech.aistar.service.UserService;

import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("mony")
public class AlipayController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;

    @GetMapping("alipay/{uid}/{price}/{now}/{names}/{nae}")
    @ResponseBody
    public String alipay(@PathVariable("uid") Integer uid, @PathVariable("names") String proName, @PathVariable("now") String nowtime, @PathVariable("price") Float orderPrice, @PathVariable("nae") String nae) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //创建API对应的request
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url + "/" + uid);
        //在公共参数中设置回跳和通知地址
        String orderNum = UUID.randomUUID().toString().replaceAll("-", "");
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url+ "/" + uid + "/" + orderNum);

        String timeout_express = "1c";
        String body = nae;
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNum + "\","
//                +"\"uid\":\""+uid+ "\","
                + "\"total_amount\":\"" + orderPrice + "\","
                + "\"subject\":\"" + proName + "\","
//                + "\"nowtime\":\"" + nowtime + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\","
                + "\"timeout_express\":\"" + timeout_express + "\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("执行支付请求后，result:" + result);
        return result;
    }

    @GetMapping("alipayReturnNotice/{uid}")
    public ModelAndView alipayReturnNotice(HttpServletRequest request, @PathVariable("uid") Integer uid) throws UnsupportedEncodingException, AlipayApiException {
        System.out.println("同步请求，支付成功后，支付宝的返回数据是：" + request);

        // 商户订单号
        String orderNum = request.getParameter("out_trade_no");
        // 支付宝交易号
        String tradeNo = request.getParameter("trade_no");
        // 付款金额
        String payPrice = request.getParameter("total_amount");
        // 用户ID
//        Integer uid = Integer.parseInt(request.getParameter("uid"));
        // 商品名称
        String nowtime = request.getParameter("timestamp");


        System.out.println("return orderNum:" + orderNum);
        System.out.println("return tradeNo:" + tradeNo);
        System.out.println("return payPrice:" + payPrice);
        System.out.println("return name:" + nowtime);
        System.out.println("return uid:" + uid); // 获取uid参数
        int menber=userService.selede(uid);
        Orders orders = orderService.seltid(uid);
        if (null != orders&&menber!=0) {

            return new ModelAndView("redirect:http://localhost:8088/dev/views/slx/index.html");
        } else {

            // 获取当前日期
            LocalDate now = LocalDate.now();
            String time = "";
            // 验证订单金额

            String vipname = "";
            int vipstatus = 0;
            int orderstatus = 1;
            if (payPrice.equals("9.00")) {
                vipname = "普通会员月卡";
                vipstatus = 1;
                LocalDate dateAfter30Days = now.plusDays(30);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (payPrice.equals("88.00")) {
                vipname = "普通会员年卡";
                vipstatus = 2;
                LocalDate dateAfter30Days = now.plusDays(365);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (payPrice.equals("14.00")) {
                vipname = "超级会员月卡";
                vipstatus = 3;
                LocalDate dateAfter30Days = now.plusDays(30);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (payPrice.equals("118.00")) {
                vipname = "超级会员年卡";
                vipstatus = 4;
                LocalDate dateAfter30Days = now.plusDays(365);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (payPrice.equals("368.00")) {
                vipname = "永久会员";
                vipstatus = 5;
                LocalDate dateAfter30Days = now.plusDays(500);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            }


//            orderService.ins(uid, orderNum, orderstatus, payPrice,payPrice, vipname, vipstatus, nowtime);
            return new ModelAndView("redirect:http://localhost:8088/dev/views/slx/index.html");
        }

    }


}
